// pages/user/address_add/address_add.js
import data1 from "../../../utils/data1";
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    params: {
      consignee: '',
      mobile: '',
      streetstr: '',
      address: '',
      province: '',
      city: '',
      district: '',
      is_default: 0
    },
    pickerData: data1,
    provinceData: [],
    cityData: [],
    areaData: [],
    modelStatus: false,
    pickerSelect: [0, 0, 0],
    areaInfo: ''
  },
  getRegion (level, parent_id) {
    const data = {
      token: app.globalData.token,
      level,
      parent_id
    }
    app.requestJs("User/getRegion",{data: data, status1: true, message: false}).then(({ data }) => {
      let name = ''
      switch (level) {
        case 1:
          name = 'provinceData'
          this.getRegion(2, data[this.data.pickerSelect[0]].id)
        break
        case 2:
          name = 'cityData'
          this.getRegion(3, data[this.data.pickerSelect[1]].id)
        break
        case 3:
          name = 'areaData'
        break
      }
      this.setData({
        [name]: data
      })
    })
  },
  submitAddress: function () {
    let data = {
      ...this.data.params
    };
    data.token = app.globalData.token;
    if (data.consignee == '') app.utilJs.toast({
      title: "请输入收货人姓名"
    });
    else if (data.mobile == '') app.utilJs.toast({
      title: "请输入收货人手机号"
    });
    else if (app.utilJs.phoneVail(data.mobile)) app.utilJs.toast({
      title: "手机号格式错误"
    });
    else if (data.streetstr == '') app.utilJs.toast({
      title: "请选择收货地址"
    });
    else if (data.address == '') app.utilJs.toast({
      title: "请输入详细地址"
    });
    else {
      app.requestJs('user/address_add', {
        data
      }).then((res) => {
        if (res.errcode == 1) {
          app.utilJs.toast({
            title: res.message
          });
          // const eventChannel = this.getOpenerEventChannel();
          // eventChannel.emit('updateData', {
          //   data: 'test'
          // });
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 200);
        } else app.utilJs.toast({
          title: res.message
        });
      })
    }
  },
  getAddressInfo: function (address_id) {
    let data = {
      token: app.globalData.token,
      address_id
    }
    app.requestJs('user/addressinfo', {
      data
    }).then((res) => {
      if (res.errcode == 1) {
        let resData = res.data || [];
        let areaInfo = [resData.province.toString(), resData.city.toString(), resData.district.toString()];
        this.setData({
          params: resData,
          areaInfo
        })
        console.log(this.data.areaInfo)
      } else app.utilJs.toast({
        title: res.message
      });
    })
  },
  bindconsigenn: function (e) {
    let value = e.detail.value;
    this.setData({
      'params.consignee': value
    })
  },
  bindmobile: function (e) {
    let value = e.detail.value;
    this.setData({
      'params.mobile': value
    })
  },
  bindaddress: function (e) {
    let value = e.detail.value;
    this.setData({
      'params.address': value
    })
  },
  binddefault: function () {
    let is_default = this.data.params.is_default;
    this.setData({
      'params.is_default': is_default == 1 ? 0 : 1
    })
  },
  cancelPicker () {
    this.setData({
      modelStatus: false
    })
  },
  closePicker () {
    let value = this.data.pickerSelect
    let provinceData = this.data.provinceData
    let cityData = this.data.cityData
    let areaData = this.data.areaData
    this.setData({
      modelStatus: false,
      'params.streetstr': provinceData[value[0]].name + '' + cityData[value[1]].name + '' + areaData[value[2]].name,
      'params.province': provinceData[value[0]].id,
      'params.city': cityData[value[1]].id,
      'params.district': areaData[value[2]].id,
    })
  },
  openPicker () {
    this.setData({
      modelStatus: true
    })
  },
  bindRegionChange: function (e) {
    let value = e.detail.value
    let provinceData = this.data.provinceData
    let cityData = this.data.cityData
    for (let index = 0; index < value.length; index++) {
      const element = value[index]
      if (element !== this.data.pickerSelect[index]) {
        switch (index) {
          case 0:
            this.getRegion(2, provinceData[element].id)
          break
          case 1:
            this.getRegion(3, cityData[element].id)
          break
        }
        break
      }
    }
    this.setData({
      pickerSelect: value
    })
    return
    // let area = e.detail.code;
    // let value = e.detail.value;
    // let areaInfo = [area[0], area[1], area[2]];
    // this.setData({
    //   areaInfo,
    //   'params.streetstr': value.join(" "),
    //   'params.province': area[0],
    //   'params.city': area[1],
    //   'params.district': area[2]
    // })
  },
  delAddress: function (e) {
    let that = this;
    wx.showModal({
      content: '确定要删除该地址吗？',
      success(res) {
        if (res.confirm) {
          let address_id = that.data.params.address_id;
          let data = {
            token: app.globalData.token,
            address_id
          }
          app.requestJs('user/deladdress', {
            data
          }).then((res) => {
            if (res.errcode == 1) {
              app.utilJs.toast({
                title: res.message
              });
              const eventChannel = that.getOpenerEventChannel()
              eventChannel.emit('delUpdate', {
                data: 'test'
              });
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                })
              }, 1200);
            } else app.utilJs.toast({
              title: res.message
            });
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let ids = options.id || '';
    wx.setNavigationBarTitle({
      title: ids == '' ? "新增地址" : "编辑地址",
    })
    console.log(ids);
    this.getRegion(1)
    if (ids == '') return
    else this.getAddressInfo(ids);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})